<?php
/**
 * Created by PhpStorm.
 * User: Sunqj
 * Date: 2018/1/11
 * Time: 下午3:55
 */

namespace app\common\model;

use Qiniu\Storage\UploadManager;
use think\Exception;
use think\facade\Db;
use think\facade\Filesystem;
use think\File;

class Storage
{
    // 存储参数
    //['image' => 'filesize:10240']
    private $params;
    public function __construct($params=[])
    {
        $this->params = $params;
    }

    /**
     * 执行上传操作
     *
     * @param string $name 文件域名
     * @param int $method 上传方式1 七牛 2 本地
     */
    public function upload($name, $method = '2')
    {

        try {
            validate($this->params)->check(request()->file());
            // 获取上传的文件信息
            $file = request()->file($name);
            if ($method == 1) {
                $this->params = config('upload.qiniu');
                return $this->uploadToQiNiu($file);
            } else {
                //保存到本地
                return $this->uploadStore($file);
            }
        } catch (\Exception $e) {
            return ['code' => 1, 'info' => $e->getMessage(), 'url'=>''];
        }
    }


    /**
     * @param File $file
     * @param string $type
     * @return array
     * @throws Exception
     */
    public function uploadStore($file)
    {
        $savename = Filesystem::disk('public')->putFile('uploads', $file);
        $result['code'] = 0;
        $result['info'] = '图片上传成功!';
        $path = str_replace('\\', '/', $savename);
        $hex = checkHex(public_path() . $path);
        if ($hex == 1) {
            return ['code' => 0, 'msg' => '请上传合法图片', 'url' => ''];
        }
        $url = '/' . $path;
        Db::name('attachment')->insertGetId(['url' => $url, 'title' => input('title', 'wxapp'), 'addtime' => time()]);
        //上传成功
        if ($url) {
            return ['code' => 0, 'msg' => '上传成功', 'url' => $url];
        } else {
            throw new Exception('文件保存失败');
        }
    }


    /**
     * 上传文件到七牛云存储
     *
     * @param File $file 文件对象
     * @return array
     * @throws Exception
     */
    private function uploadToQiNiu($file)
    {

        // 获取文件信息
        $fileInfo = $this->getFileInfo($file);

        try {
            // 构建鉴权对象
            $auth = new \Qiniu\Auth($this->params['access_key'], $this->params['secret_key']);

            // 生成上传 Token
            $token = $auth->uploadToken($this->params['bucket']);

            // 初始化 UploadManager 对象
            $manager = new UploadManager();

            // 进行文件上传操作。
            list($result, $error) = $manager->putFile($token, $fileInfo['name'], $fileInfo['path']);

            // 上传成功
            if ($error === null) {
                // 返回上传后的地址
                $url = "{$this->params['domain']}/{$result['key']}";
                return ['code' => 0, 'msg' => '上传成功', 'url' => $url];
            } else { // 上传失败
                return ['code' => 1, 'msg' => '七牛云服务异常，上传失败！！！'];
            }
        } catch (\Exception $exception) {
            return ['code' => 1, 'msg' => $exception->getMessage()];
        }
    }


    /**
     * 为七牛云处理文件信息
     *
     * @param File $file
     * @return array
     */
    private function getFileInfo($file)
    {
        // 文件名
        $filename = $file->getFilename();

        // 文件扩展
        $extension = substr($filename, strripos($filename, '.'));

        // 文件名
        $fullName = md5(microtime(true) . $filename) . $extension;

        // 返回文件信息
        return [
            'name' => $fullName,
            'path' => $file->getPathname()
        ];
    }
}